package com.waltercedric.tuxdroid.buildserver.teamcity;

import org.apache.log4j.Logger;

import com.tuxisalive.api.TuxAPI;
import com.tuxisalive.api.TuxAPIConst;

/**
 * TuxDroidBuild Copyright (C) 2009 Cedric Walter - www.waltercedric.com
 * 
 * This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
 * This is free software, and you are welcome to redistribute it under certain
 * conditions; type `show c' for details.
 * 
 * @author Cedric Walter - www.waltercedric.com
 */
public class TuxDroidNotificator  {

	protected static final String TYPE = "TuxDroidNotifier";
	protected static final String TYPE_NAME = "Tux Droid Notifier";

	private static Logger logger = Logger.getLogger(TuxDroidNotificator.class.getName());


	public void doNotifications(String freeUserChoice, String defaultMessage, String ipAdress, Integer port) {
		logger.info("Trying to connect to Tux Droid at <" + ipAdress + "> on port <" + port + ">.");
		TuxAPI tux = new TuxAPI(ipAdress, port);

		try {

			tux.server.autoConnect(TuxAPIConst.CLIENT_LEVEL_RESTRICTED, "login", "password");

			tux.server.waitConnected(10.0);
			if (tux.server.getConnected()) {
				tux.dongle.waitConnected(10.0);
				if (tux.dongle.getConnected()) {

					if (tux.radio.waitConnected(10.0)) {

						for (String voice : tux.tts.getVoices()) {
							logger.debug("available voice" + voice);
						}

						if (tux.tts.getVoices().size() <= 0) {
							logger.error("No tts voices are registered! Tux Droid wont be able to speak!");
						}

						if (freeUserChoice != null && freeUserChoice.trim().length() > 0) {
							logger.info("Tux droid will play a text or attitune <" + freeUserChoice + ">");
							playTux(freeUserChoice, tux);
						} else {
							logger.info("Tux Droid will use default message <" + defaultMessage + ">.");
							tux.tts.speak(defaultMessage);
						}
					} else {
						logger.error("Can not connect to Tux droid radio.");
					}
				} else {
					logger.error("Can not connect to Tux droid dongle.");
				}
			} else {
				logger.error("Can not connect to Tux droid server <" + ipAdress + "," + port + ">.");
			}
		} finally {
			tux.destroy();
			logger.info("destroy Tux API");
		}

	}

	protected void playTux(String freeUserChoice, TuxAPI tux) {
		
		if (freeUserChoice.contains("#")) {
			freeUserChoice = freeUserChoice.replace("#", "");
			tux.attitune.load(freeUserChoice);
			tux.attitune.play();
			tux.attitune.stop();
		} else {
			tux.tts.speak(freeUserChoice);
		}

	}

	public String getDisplayName() {
		return TYPE_NAME;
	}

	public String getNotificatorType() {
		return TYPE;
	}

}
